import {
  init as AmapGeolocationInit,
  Geolocation
} from 'react-native-amap-geolocation'
import { createAction } from 'redux-actions'
import { UPDATE_LANDMARK_TYPE } from '../types/landmark'
import DeviceStorage from '../../utils/DeviceStorage'
import { cityPositioning } from 'src/utils/RequestAPI'
import { CustomPermissions } from 'src/utils/PermissionsUtil'
import { isLegalCity } from 'src/utils/ConfigUtil'
import { AMAPAPPKEY_IOS, AMAPAPPKEY_ANDROID } from 'src/config/index'

/* 从本地读取地理位置 */
export const GET_LOCAL_LANDMARK_ACTION = createAction(
  UPDATE_LANDMARK_TYPE,
  () => {
    return new Promise(resolve => {
      Promise.all([
        DeviceStorage.get('landmark'),
        AmapGeolocationInit({
          ios: AMAPAPPKEY_IOS,
          android: AMAPAPPKEY_ANDROID
        })
      ]).then(([payload, initRes]) => {
        resolve(payload)
      })
    })
  }
)
/**
 * 更新地理位置
 */
export const UPDATE_LANDMARK_ACTION = createAction(
  UPDATE_LANDMARK_TYPE,
  payload => payload
)

export const GET_HOME_CITY_ACTION = createAction(UPDATE_LANDMARK_TYPE, () => {
  let currentLocation = {}
  return new Promise((resolve, reject) => {
    CustomPermissions({ type: 'location' })
      .then(response => {
        console.log('location', response)
        return getCurrentPositionPromise()
      })
      .then(({ lat, lng }) => {
        currentLocation = { lat, lng }
        if (lat && lng) {
          return cityPositioning({ query: { lat, lng } })
        } else {
          reject({
            cityName: '北京'
          })
        }
      })
      .then(({ data: cityName }) => {
        console.log('cityPositioning', {
          cityName
        })
        if (isLegalCity(cityName)) {
          resolve({
            cityName,
            currentLocation
          })
        } else {
          reject({
            cityName: '北京'
          })
        }
      })
      .catch(() => {
        reject({
          cityName: '北京'
        })
      })
  })
})
export const GET_LANUCH_CURRENT_LOCATION_ACTION = createAction(UPDATE_LANDMARK_TYPE, () => {
  return new Promise((resolve, reject) => {
    CustomPermissions({ type: 'location' })
      .then(response => {
        console.log('location', response)
        return getCurrentPositionPromise()
      })
      .then(({ lat, lng }) => {
        resolve({
          currentLocation: { lat, lng }
        })
      })
  })
})

/**
 * 检测定位权限及获取当前地址
 */
export function getCurrentPosition () {
  return CustomPermissions({
    type: 'location',
    showAlert: true,
    alertConfig: {
      title: '温馨提示',
      subtitle: '人职初需要访问您的位置',
      btnTexts: ['取消', '去开启']
    }
  }).then(response => {
    console.log('location', response)
    return getCurrentPositionPromise()
  })
}

export function getCurrentPositionPromise () {
  return new Promise((resolve, reject) => {
    Geolocation.getCurrentPosition(
      ({ coords: { latitude: lat, longitude: lng } }) => {
        console.log('getCurrentPositionPromise', { lat, lng })
        resolve({ lat, lng })
      },
      error => {
        console.info('getCurrentPositionPromiseError', error)
        reject(error)
      }
    )
  })
}
